import * as types from '../mutation-types'
import api from 'api'
import phones from 'alert-phones'
import _ from 'lodash'

// initial state
const state = {
  alertList: [],
  currAlerts: []
}

const actions = {
  // let devices = [
  //   {
  //     name: '工程部平板',
  //     type: 1,
  //     status: 1,
  //     user: '闲置',
  //     location: {
  //       lng: 116.424,
  //       lat: 39.935
  //     }
  //   }
  // ]

  // 弹出一条告警提示 alert格式:
  // {
  //   name: 'XXXX',
  //   message: '总有功功率偏低, 当前: 0.2',
  //   time: new Date()
  // }
  showAlert ({ commit }, alert) {
    if (!alert.name) return console.warn('告警信息没有name字段')
    if (!alert.message) return console.warn('告警信息没有message字段')
    alert.time = alert.time || new Date()

    // 发送告警短信
    if (Array.isArray(phones)) {
      _.forEach(phones, (phone) => {
        api.message.sendMessage(phone, {
          place: alert.name,
          device: alert.device,
          desc: alert.message,
          value: alert.value + ''
        })
      })
    }
    commit(types.SHOW_ALERT, alert)
    // setTimeout(() => {
    //   commit(types.HIDE_ONE_ALERT, alert)
    // }, 5000)
  },

  hideAlert ({ commit }, alert) {
    commit(types.HIDE_ONE_ALERT, alert)
  },

  // 添加一条告警记录
  pushAlert ({ commit }, alert) {
    commit(types.PUSH_ALERT, alert)
  },

  // 更新告警列表
  updateAlerts ({ commit }, alerts) {
    commit(types.UPDATE_ALERTS, alerts)
  }
}

const getters = {
  alertList (state) {
    return state.alertList
  },
  currAlerts () {
    return state.currAlerts
  }
}

// mutations
const mutations = {
  [types.SHOW_ALERT] (state, alert) {
    state.currAlerts.unshift(alert)
  },
  [types.HIDE_ONE_ALERT] (state, alert) {
    let index = state.currAlerts.indexOf(alert)
    state.currAlerts.splice(index, 1)
  },
  [types.PUSH_ALERT] (state, alert) {
    state.alertList.push(alert)
  },
  [types.UPDATE_ALERTS] (state, alerts) {
    state.alertList = alerts
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
